<?php

namespace app\admin\controller;

use app\common\controller\Admin;

/**
 * 产品
 * Class Borrow
 * @package app\admin\controller
 */
class Borrow extends Admin
{

    /**
     * 产品列表
     * @return mixed
     */
    public function index()
    {
        $map = array();

        $list = model('Borrow')->where($map)->order('id desc')->paginate(5, false, array(
            'query' => $this->request->param()
        ));

        $data = array(
            'list' => $list,
            'page' => $list->render(),
        );
        $this->assign($data);
        $this->setMeta('产品列表');
        return $this->fetch();
    }

    /**
     * 添加产品
     * @return mixed
     */
    public function add()
    {

        $borrow = model('Borrow');

        if ($this->request->isPost()) {
            $result = $borrow->change();
            if ($result) {
                $this->success("添加成功！", url('borrow/index'));
            } else {
                $this->error($borrow->getError());
            }
        } else {

            $info = [];
            $data = array(
                'info' => $info,
                'keyList' => $borrow->keyList,
            );
            $this->assign($data);
            $this->setMeta('添加产品');
            return $this->fetch('public/edit');
        }
    }


    /**
     * 编辑产品
     * @param null $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = null)
    {

        $ad = model('borrow');

        if ($this->request->isPost()) {

            $result = $ad->change();
            if ($result) {
                $this->success("修改成功！", url('borrow/index'));
            } else {
                $this->error($ad->getError());
            }

        } else {

            $info = db('borrow')->where(array('id' => $id))->find();
            if (!$info) {
                $this->error("非法操作！");
            }
            $data = array(
                'info' => $info,
                'keyList' => $ad->keyList,
            );
            $this->assign($data);
            $this->setMeta("编辑产品");
            return $this->fetch('public/edit');
        }
    }

    /**
     * 删除产品
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete()
    {

        $id = $this->getArrayParam('id');

        if (empty($id)) {
            $this->error("非法操作！");
        }

        if (db('borrow_invest')->where(['borrow_id' => $id])->count() > 0) {
            $this->error("存在投资记录，不可删除！");
        }

        $result = db('borrow')->where(['id' => $id])->delete();
        if ($result) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

}